package com.dmai.capacity.platform.oauth.common.service.impl;

import java.util.List;
import java.util.Map;

import com.dmai.capacity.platform.common.model.OauthClient;
import com.dmai.capacity.platform.db.service.impl.ServiceImpl;
import com.dmai.capacity.platform.oauth.common.mapper.OauthClientMapper;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dmai.capacity.platform.common.constant.SecurityConstants;
import com.dmai.capacity.platform.common.dto.PageResult;
import com.dmai.capacity.platform.common.dto.ResponseEntity;
import com.dmai.capacity.platform.redis.repository.RedisRepository;
import com.dmai.capacity.platform.oauth.common.service.IOauthClientService;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@Service
public class OauthClientServiceImpl extends ServiceImpl<OauthClientMapper, OauthClient> implements IOauthClientService {

    @Autowired
    private RedisRepository redisRepository;

    @Autowired(required = false)
    private PasswordEncoder passwordEncoder;


    @Override
    public ResponseEntity saveClient(OauthClient oauthClient) throws Exception {
        oauthClient.setClientSecret(passwordEncoder.encode(oauthClient.getClientSecretStr()));
        String clientId = oauthClient.getClientId();
        this.saveOrUpdate(oauthClient);
        return ResponseEntity.succeed("操作成功");
    }

    @Override
    public PageResult<OauthClient> listClient(Map<String, Object> params, boolean isPage) {
        Page<OauthClient> page;
        if (isPage) {
            page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
        } else {
            page = new Page<>(1, -1);
        }
        List<OauthClient> list = baseMapper.findList(page, params);
        page.setRecords(list);
        return PageResult.<OauthClient>builder().data(list).code(0).count(page.getTotal()).build();
    }

    @Override
    public boolean delClient(long id) {
        String clientId = baseMapper.selectById(id).getClientId();
        redisRepository.del(clientRedisKey(clientId));
        return baseMapper.deleteById(id) > 0 ? true : false;
    }

    @Override
    @Cacheable(value = "auth", key = "#clientId", unless = "#result == null")
    public OauthClient loadClientByClientId(String clientId, String requestUrl) {
        return baseMapper.findByClientId(clientId, requestUrl);
    }

    private String clientRedisKey(String clientId) {
        return SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId;
    }
}
